import os
from mgamedev.py_lib.decorator import singleton
import json
from ccpm.auth.gitee_auth import GiteeLogin
from ccpm.auth.heyzf_auth import HeyzfLogin
from ccpm.constants import Constant

FILE_CACHE_TAR = Constant.MODULE_CACHE_FILE


def _file_save(cont):
    with open(FILE_CACHE_TAR, "w") as fp:
        fp.write(cont)


def _file_get():
    with open(FILE_CACHE_TAR, "r") as fp:
        fp.read(cont)


class eCacheType:
    file = 1,
    sqlite = 2


@singleton
class ModelUsr:

    _type = eCacheType.file

    def __init__(self):
        self._diccont = {}

    def __chk_local(self):
        if os.path.isfile(FILE_CACHE_TAR):
            fp = open(FILE_CACHE_TAR, "r")
            fcont = fp.read()
            if len(fcont) == 0:
                fcont = "{}"
            try:
                fdic = json.loads(fcont)
            except json.JSONDecodeError as jerr:
                fdic = {}
            self._diccont.update(fdic)
            fp.close()

    def flush(self):
        if self._type == eCacheType.file:
            _file_save(json.dumps(self._diccont, sort_keys=True, indent=4))
        else:
            # todo sqlite
            pass

    def clear(self):
        self._diccont = {}
        if os.path.isfile(FILE_CACHE_TAR):
            os.remove(FILE_CACHE_TAR)

    def get(self, key):
        return self._diccont.get(key)

    def get_name(self):
        if self.get("authtype") == "gitee":
            self.get("name")
        elif self.get("authtype") == "heyzf":
            return self.get("nickname")

    def set_dic(self, ndic):
        self._diccont.update(ndic)

    def chk_heyzf_token(self, acctoken, reftoken):
        gid = self.get("gid")
        (issuc, ret) = HeyzfLogin.get_heyzfusr(gid)
        if (not issuc):
            if ret.get("r") == 104:
                (issuc, ret) = HeyzfLogin.post_refreshtoken(gid, reftoken)
                if (issuc):
                    self._diccont.update(ret)
                    self.flush()
                    (issuc, ret) = HeyzfLogin.get_heyzfusr(gid)
                    if (issuc):
                        self._diccont.update(ret.get("data"))
                        return True
            return False
        self._diccont.update(ret.get("data"))
        return ret

    def chk_gitee_token(self, acctoken, reftoken):
        (issuc, ret) = GiteeLogin.get_giteeusr(acctoken)
        if (not issuc):
            if ret.status_code == 401:
                (issuc_, invoice) = GiteeLogin.post_refreshtoken(reftoken)
                if (issuc_):
                    self._diccont.update(invoice)
                    self.flush()
                    (issuc, ret) = GiteeLogin.get_giteeusr(
                        self.get("access_token"))
                    if (issuc):
                        self._diccont.update(ret)
                        return True
            return False
        self._diccont.update(ret)
        return ret

    def chk_usrinfo(self, authtype):
        self.__chk_local()
        if len(self._diccont) == 0:
            print("Run ccpm command:<adduser> first!")
            return False
        if authtype != self._diccont["authtype"]:
            print("Del old login type <%s> cache info!" %
                  self._diccont.get("authtype"))
            self.clear()
            return False
        self._diccont["authtype"] = authtype
        acctoken = self.get("access_token")
        rfacctoken = self.get("refresh_token")
        ret = None
        if authtype == "gitee":
            ret = self.chk_gitee_token(acctoken, rfacctoken)
        elif authtype == "heyzf":
            ret = self.chk_heyzf_token(acctoken, rfacctoken)
        if ret:
            self._diccont.update(ret)
            return True
        else:
            self.clear()
            return False
